package cn.stylefeng.guns.modular.demos.controller;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.service.AuthService;
import cn.stylefeng.guns.modular.fuwu.entity.Fuwu;
import cn.stylefeng.guns.modular.fuwu.entity.Leibie;
import cn.stylefeng.guns.modular.fuwu.service.FuwuService;
import cn.stylefeng.guns.modular.fuwu.service.LeibieService;
import cn.stylefeng.guns.modular.loginStatus.entity.LoginStatus;
import cn.stylefeng.guns.modular.loginStatus.service.LoginStatusService;
import cn.stylefeng.guns.modular.orderCenter.entity.Order;
import cn.stylefeng.guns.modular.orderCenter.service.OrderService;
import cn.stylefeng.guns.modular.ortherService.entity.OrtherService;
import cn.stylefeng.guns.modular.ortherService.service.OrtherServiceService;
import cn.stylefeng.guns.modular.pageConfig.entity.PageConfig;
import cn.stylefeng.guns.modular.pageConfig.service.PageConfigService;
import cn.stylefeng.guns.modular.tpls.entity.Tpls;
import cn.stylefeng.guns.modular.tpls.model.params.TplsParam;
import cn.stylefeng.guns.modular.tpls.service.TplsService;
import cn.stylefeng.guns.sys.core.alipay.AliPayUtil;
import cn.stylefeng.guns.sys.core.alipay.AlipayConfig;
import cn.stylefeng.guns.sys.core.auth.cache.SessionManager;
import cn.stylefeng.guns.sys.core.util.AppQrCode;
import cn.stylefeng.guns.sys.core.util.OrderCodeMaker;
import cn.stylefeng.guns.sys.core.util.WxTool;
import cn.stylefeng.guns.sys.core.wechatpay.WechatPayUtils;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.response.ResponseData;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.CloseOrderRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录控制器
 *
 * @author fengshuonan
 * @Date 2017年1月10日 下午8:25:24
 */
@Controller
public class PageCtrlController extends BaseController {

    @Autowired
    private AuthService authService;

    @Autowired
    private UserService userService;

    @Autowired
    private SessionManager sessionManager;
    
    @Autowired
    private FuwuService fuwuService;
    
    @Autowired
    private LeibieService leibieService;
    
    @Autowired
    private TplsService tplsService;
    
    @Autowired
    private LoginStatusService loginStatusService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private PageConfigService pageConfigService;
    
    @Autowired
    private OrtherServiceService ortherServiceService;
    
    /**
     * 跳转到主页
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
    	
    	if(LoginContextHolder.getContext().hasLogin()&&LoginContextHolder.getContext().isAdmin()) {
    		return REDIRECT + "/admin";
    	}
    	
    	PageConfig pc = pageConfigService.getById(1);
    	
    	model.addAttribute("pageInfo", pc);
    	
    	List<Fuwu> fws = fuwuService.list(new QueryWrapper<Fuwu>().last("limit 4"));
		
		List<Tpls> tpls = tplsService.list(new QueryWrapper<Tpls>().last("order by createTime desc limit 4"));
		List<Tpls> tjtpls = tplsService.list(new QueryWrapper<Tpls>().last("order by RAND() limit 4"));
    	
    	model.addAttribute("fw", fws);
    	model.addAttribute("def", fws.get(0).getId());
    	model.addAttribute("tpls", tpls);
    	model.addAttribute("tjtpls", tjtpls);
    	
    	List<OrtherService> lo = ortherServiceService.list();
    	model.addAttribute("os", lo);
    	
    	return "/home.html";
    }
    
    @RequestMapping(value = "/index.html", method = RequestMethod.GET)
    public String home(Model model) {
    	
    	if(LoginContextHolder.getContext().hasLogin()&&LoginContextHolder.getContext().isAdmin()) {
    		return REDIRECT + "/admin";
    	}
    	
    	PageConfig pc = pageConfigService.getById(1);
    	
    	model.addAttribute("pageInfo", pc);
    	
    	List<Fuwu> fws = fuwuService.list(new QueryWrapper<Fuwu>().last("limit 4"));
		
		List<Tpls> tpls = tplsService.list(new QueryWrapper<Tpls>().last("order by createTime desc limit 4"));
		List<Tpls> tjtpls = tplsService.list(new QueryWrapper<Tpls>().last("order by RAND() limit 4"));
    	
    	model.addAttribute("fw", fws);
    	model.addAttribute("def", fws.get(0).getId());
    	model.addAttribute("tpls", tpls);
    	model.addAttribute("tjtpls", tjtpls);
    	
    	return "/home.html";
    }

    /**
     * 跳转到主页
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping(value = "/list-{fw}-{fl}-{px}-{page}.html", method = RequestMethod.GET)
    public String list(Model model,@PathVariable(value = "fw", required = false) Long fw,@PathVariable(value = "fl", required = false) Long fl,@PathVariable(value = "px", required = false) Integer px,@PathVariable(value = "page", required = false) Integer page
    		,String keyword) {
    	
    	//判断是否管理员 直接跳转后台
    	if(LoginContextHolder.getContext().hasLogin()&&LoginContextHolder.getContext().isAdmin()) {
    		return REDIRECT + "/admin";
    	}
    	
    	
    	PageConfig pc = pageConfigService.getById(1);
    	
    	model.addAttribute("pageInfo", pc);
    	
    	//获取服务列表
    	
    	String fwstr = "";
    	String flstr = "";
    	String pxstr = "";
    	
    	List<Fuwu> fws = fuwuService.list();
    	//设置当前选中状态
    	if(ToolUtil.isNotEmpty(fw)) {
    		for(int i=0;i<fws.size();i++) {
    			if(fw.equals(fws.get(i).getId())) {
    				fws.get(i).setTag("sel");
    				fwstr = fws.get(i).getSerName();
    			}
    		}
    	}else {
    		fws.get(0).setTag("sel");
    		fwstr = fws.get(0).getSerName();
    	}
    	
    	//获取分类别表
    	List<Leibie> lbs = leibieService.list();
    	//设置当前选中状态
    	if(ToolUtil.isNotEmpty(fl)) {
    		for(int i=0;i<lbs.size();i++) {
    			if(fl.equals(lbs.get(i).getId())) {
    				lbs.get(i).setTag("sel");
    				flstr = lbs.get(i).getName();
    			}
    		}
    	}
    	
    	model.addAttribute("fuwu", fws);
    	model.addAttribute("lb", lbs);
    	
    	model.addAttribute("fw", fw);
    	if(ToolUtil.isNotEmpty(fl)) {
    		model.addAttribute("fl", fl);
    	}else {
    		model.addAttribute("fl", 0);
    	}
    	
    	if(ToolUtil.isNotEmpty(px)) {
    		model.addAttribute("px", px);
    		if(px==1)
    			pxstr = "价格优惠的";
    		
    		if(px == 2) 
    			pxstr = "最新的";
    		
    		if(px == 0) 
    			pxstr = "";
    	}else {
    		model.addAttribute("px", 0);
    	}
    	
    	if(ToolUtil.isNotEmpty(page)) {
    		model.addAttribute("page", page);
    	}else {
    		model.addAttribute("page", 1);
    	}
    	
    	Integer offset = (page - 1)*20;
    	
    	TplsParam tp = new TplsParam();
    	
    	tp.setFw(fw);
    	tp.setFl(fl);
    	tp.setPx(px);
    	tp.setPage(page);
    	tp.setOffset(offset);
    	
    	//获取模板列表
    	
    	int s = 0;
    	
    	String sql = "";
    	String sql2 = "";
    	model.addAttribute("keyword", "");
    	model.addAttribute("s", 0);
    	if(ToolUtil.isNotEmpty(keyword)) {
    		model.addAttribute("keyword", keyword);
    		s=1;
    		sql += " and name like '%"+keyword+"%'";
    		sql2 += " and name like '%"+keyword+"%'";
    	}
    	
    	if(fw!=0) {
    		sql += " and fwid = "+fw;
    		sql2 += " and fwid = "+fw;
    	}
    	if(fl!=0) {
    		sql += " and flid = "+fl;
    		sql2 += " and flid = "+fl;
    	}
    	if(px==1) {
    		sql += " order by jiage ASC";
    	}
    	if(px==2) {
    		sql += " order by createTime DESC ";
    	}
    	
    	sql += " limit 20 offset "+ offset;
    	
    	model.addAttribute("s", s);
    	
    	System.out.println(sql);
    	
//    	List<TplsResult> list = tplsService.listbyquery(tp);
    	Integer num = tplsService.count(new QueryWrapper<Tpls>().select("id").eq("1", 1).last(sql2));
    	List<Tpls> list = tplsService.list(new QueryWrapper<Tpls>()
    			.select("id","name","mainPic","detail","ms","jiage","backColor","sy","sizeStr","tags","zuozhe","DATE_FORMAT(createTime, '%Y-%m-%d')")
    			.eq("1", 1)
    			.last(sql));
    	model.addAttribute("list", list);
    	model.addAttribute("listSize", list.size());
    	model.addAttribute("count", num);
    	model.addAttribute("size", 20);
    	model.addAttribute("now", page);
    	
    	String html = getpaging(num,20,page,fw,fl,px,s,keyword);
    	
    	model.addAttribute("pageNum", html);
    	model.addAttribute("webtitle", pxstr+flstr+fwstr);
    	return "/list.html";
    }
    
    
    
    /**
     * 跳转到我的订单
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping(value = "/orderCenter.html", method = RequestMethod.GET)
    public String orderCenter(Model model) {
    	
    	if(!LoginContextHolder.getContext().hasLogin()) {
    		return REDIRECT + "/";
    	}
    	
    	//判断是否管理员 直接跳转后台
    	if(LoginContextHolder.getContext().hasLogin()&&LoginContextHolder.getContext().isAdmin()) {
    		return REDIRECT + "/admin";
    	}
    	
    	
    	PageConfig pc = pageConfigService.getById(1);
    	
    	model.addAttribute("pageInfo", pc);
    	
    	model.addAttribute("webtitle", "订单中心");
    	
    	
    	return "/orderCenter.html";
    }
    
    
    private String getpaging(Integer num, Integer box, Integer page, Long fw, Long fl, Integer px,Integer s,String key) {
    	
    	int ts = 9;
    	
    	int totalPage = (num + box - 1) / box;
    	
    	int min = (int) (page - Math.floor(ts/2));
    	if(min > totalPage - ts) {
    		min = totalPage - ts + 1;
    	}
    	if(min <=1) {
    		min=1;
    	}
    	
    	
    	int max = (int) (page + Math.floor(ts/2));
    	if(max < ts) {
    		max = ts;
    	}
    	if(max>totalPage) {
    		max = totalPage;
    	}
    	
    	int[] se = ArrayUtil.range(min, max+1);
    	String html = "";
    	
    	String q="";
    	if(s==1) {
    		q="?keyword="+key;
    	}
    	
    	if(page>1) {
			html += "<a href='list-"+fw+"-"+fl+"-"+px+"-"+(page-1)+".html"+q+"' class='btn page_prev router-link-active' rel='prev'><i class='fa fa- Example ofangle-left'></i></a>";
		}
    	for(int i=0;i<se.length;i++) {
    		String c = "";
    		if(se[i]==page) {
    			c= "current";
    		}
    		
    		html += "<a href='/list-"+fw+"-"+fl+"-"+px+"-"+se[i]+".html"+q+"' class='page_nav "+c+"'>"+se[i]+"</a>";
    		
    		
    	}
    	if(totalPage>1&&page<totalPage) {
			html += "<a href='list-"+fw+"-"+fl+"-"+px+"-"+(page+1)+".html"+q+"' class='btn page_next' rel='prev'><i class='fa fa- Example ofangle-left'></i></a>";
		}
    	
    	
    	return html;
	}

	/**
     * 跳转到详情页
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping(value = "/detail/{id}.html", method = RequestMethod.GET)
    public String detail(Model model,@PathVariable Long id) {
    	
    	if(LoginContextHolder.getContext().hasLogin()&&LoginContextHolder.getContext().isAdmin()) {
    		return REDIRECT + "/admin";
    	}
    	
    	PageConfig pc = pageConfigService.getById(1);
    	
    	model.addAttribute("pageInfo", pc);
    	
    	Tpls tpls = tplsService.getOne(new QueryWrapper<Tpls>()
    			.select("id","name","mainPic","detail","ms","jiage","backColor","sy","sizeStr","tags","zuozhe","DATE_FORMAT(createTime, '%Y-%m-%d') AS createTime")
    			.eq("id", id));
    	model.addAttribute("data", tpls);
    	model.addAttribute("id", id);
    	
    	return "/detail.html";
    }
    
    
    
    /**
     * 跳转到订单页
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping(value = "/order/{id}.html", method = RequestMethod.GET)
    public String order(Model model,@PathVariable Long id) {
    	
    	
    	PageConfig pc = pageConfigService.getById(1);
    	
    	model.addAttribute("pageInfo", pc);
    	
    	
    	Order order = orderService.getOne(new QueryWrapper<Order>().eq("tid", id)
    			.eq("uid", LoginContextHolder.getContext().getUserId()));
    	
    	if(order!=null&&order.getState()==1) {//已支付
    		//直接跳转下载
    		return REDIRECT + "/orderDetail/"+order.getOrderNum()+".html";
    	}
    	
    	Tpls tpls = tplsService.getById(id);
    	model.addAttribute("data", tpls);
    	model.addAttribute("id", id);
    	
    	
    	
    	return "/order.html";
    }
    
    
    
    /**
     * 获取登录二维码
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping("/getLoginQrCode")
    @ResponseBody
    public ResponseData getLoginQrCode(HttpServletResponse response) {
    	
    	LoginStatus ls = new LoginStatus();
    	
    	ls.setCreateTime(new DateTime());
    	ls.setState(0);
    	
    	loginStatusService.save(ls);
    	
    	Long id = ls.getId();
    	
    	AppQrCode aqc = new AppQrCode();
    	
    	aqc.setPage("pages/home/index");
    	aqc.setScene("stid/"+id);
    	aqc.setEnv_version("trial");
    	
    	String base64 = "";
    	
    	try {
			base64 = WxTool.inputStream2Base64(WxTool.getQRCode(aqc));
		} catch (ClientProtocolException e1) {
			return ResponseData.error("获取登录码失败");
		} catch (IOException e1) {
			return ResponseData.error("获取登录码失败");
		} catch (Exception e1) {
			return ResponseData.error("获取登录码失败");
		}
    	
    	Map<String,Object> mso = new HashMap<String, Object>();
    	
    	mso.put("qrcode", base64);
    	mso.put("stid", id);
        return ResponseData.success(mso);
    }
    
    
    /**
     * 获取登录二维码
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping("/getLoginStatus")
    @ResponseBody
    public ResponseData getLoginStatus(Long stid) {
    	LoginStatus ls = loginStatusService.getById(stid);
    	
    	if(ls.getState() == 2) {
    		authService.addLoginCookie(ls.getTokenStr());
    	}
    	
    	return ResponseData.success(ls);
    }
    
    
    
    
    
    
    
    /**
     * 跳转到详情页
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping(value = "/gen/{type}.html", method = RequestMethod.GET)
    public String genCode(Model model,@PathVariable Long type) {
    	
    	if(LoginContextHolder.getContext().hasLogin()&&LoginContextHolder.getContext().isAdmin()) {
    		return REDIRECT + "/admin";
    	}
    	
    	PageConfig pc = pageConfigService.getById(1);
    	
    	model.addAttribute("pageInfo", pc);
    	
    	OrtherService os = ortherServiceService.getById(type);
    	
    	model.addAttribute("data", os);
    	
    	return "/genservice.html";
    }
    
    
    /**
     * 跳转到详情页
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping(value = "/genorder/{type}.html", method = RequestMethod.GET)
    public String genorder(Model model,@PathVariable Long type) {
    	
    	if(LoginContextHolder.getContext().hasLogin()&&LoginContextHolder.getContext().isAdmin()) {
    		return REDIRECT + "/admin";
    	}
    	
    	PageConfig pc = pageConfigService.getById(1);
    	
    	model.addAttribute("pageInfo", pc);
    	
    	OrtherService os = ortherServiceService.getById(type);
    	
    	model.addAttribute("data", os);
    	
    	return "/genorder.html";
    }
    
    
    
    /**
     * 跳转到订单页
     *
     * @author fengshuonan
     * @throws IOException 
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping(value = "/createOrder.html", method = RequestMethod.GET)
    public String createOrder(Long tid) throws IOException {
    	
    	if(!LoginContextHolder.getContext().hasLogin()||ToolUtil.isEmpty(tid)) {
    		return REDIRECT+"/";
    	}
    	
    	Tpls tpl = tplsService.getById(tid);
    	
    	if(ToolUtil.isEmpty(tpl)) {
    		return REDIRECT+"/";
    	}
    	
    	Order oo = orderService.getOne(new QueryWrapper<Order>()
    			.eq("tid", tid).eq("uid", LoginContextHolder.getContext().getUserId()));
    	
    	if(oo!=null&&oo.getState()!=1) {
    		if(ToolUtil.isNotEmpty(oo.getPayType())) {//已经下过订单  删除重新下
    			
    			if("alipay".equals(oo.getPayType())) {
    				AliPayUtil.close(oo.getOrderNum());
    			}
    			if("wechatpay".equals(oo.getPayType())) {
    				CloseOrderRequest request = new CloseOrderRequest();
    				request.setOutTradeNo(oo.getOrderNum());
    				WechatPayUtils.closeOrder(request);
    			}
    			orderService.removeById(oo.getId());
    			oo=null;
    		}
    	}
    	
    	
    	if(oo!=null&&oo.getState()==1) {
    		return REDIRECT + "/orderDetail/"+oo.getOrderNum()+".html";
    	}else {
    		Order order = new Order();
        	order.setCreateTime(DateFormatUtils.format(new DateTime(), "yyyy-MM-dd HH:mm:ss"));
        	order.setOrderNum(OrderCodeMaker.genOrderNumber("OT"));
        	order.setTjiage(tpl.getJiage());
        	order.setTid(tid);
        	order.setTms(tpl.getMs());
        	order.setTname(tpl.getName());
        	order.setTpic(tpl.getMainPic());
        	order.setUid(LoginContextHolder.getContext().getUserId());
        	order.setState(0);
        	
        	if(orderService.save(order)) {
        		return REDIRECT + "/orderDetail/"+order.getOrderNum()+".html";
        	}else {
        		return REDIRECT+"/";
        	}
    	}
    }
    
    
    /**
     * 跳转到订单页
     *
     * @author fengshuonan
     * @throws AlipayApiException 
     * @throws IOException 
     * @Date 2018/12/23 5:41 PM
     */
	@RequestMapping(value = "/orderDetail/{orderNum}.html", method = RequestMethod.GET)
    public String payOrder(@PathVariable String orderNum,Model model) throws AlipayApiException, IOException {
    	
    	if(!LoginContextHolder.getContext().hasLogin()||ToolUtil.isEmpty(orderNum)) {
    		return REDIRECT+"/";
    	}
    	
    	sessionManager.delSession("PT"+orderNum);
    	
    	Order order = orderService.getOne(new QueryWrapper<Order>().eq("orderNum", orderNum));
    	
    	if(ToolUtil.isEmpty(order)) {
    		return REDIRECT+"/";
    	}
    	
    	if(ToolUtil.isNotEmpty(order.getPayType())) {
    		if("alipay".equals(order.getPayType())) {
    			Map<String,Object> resmap = AliPayUtil.queryOrderStatus(orderNum);
    			System.out.println(resmap);
    		}
    		
    		if("wechatpay".equals(order.getPayType())) {
    			QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
    			request.setOutTradeNo(order.getOrderNum());
    			WechatPayUtils.queryOrderByOutTradeNo(request);
    			
    		}
    		
    		
    	}
    	
    	//支付宝确认是否支付
    	Map<String,Object> resmap = AliPayUtil.queryOrderStatus(orderNum);
    	System.out.println(resmap);
    	
    	PageConfig pc = pageConfigService.getById(1);
    	
    	model.addAttribute("pageInfo", pc);
    	
    	Tpls tpls = tplsService.getById(order.getTid());
    	model.addAttribute("data", tpls);
    	model.addAttribute("order", order);
    	model.addAttribute("id", order.getTid());
    	
    	
    	return "/payOrder.html";
    }
    
    
    /**
     * 支付操作
     *
     * @author fengshuonan
     * @throws IOException 
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping("/topay")
    @ResponseBody
    public ResponseData topay(String orderNumber,String paytype) {
    	
    	if(ToolUtil.isEmpty(paytype)||ToolUtil.isEmpty(orderNumber)) {
    		return ResponseData.error("支付参数错误");
    	}
    	
    	Order order = orderService.getOne(new QueryWrapper<Order>()
    			.eq("orderNum", orderNumber));
    	
    	if(order==null) {
    		return ResponseData.error("订单不存在");
    	}
    	
    	if(order.getState()==1) {
    		return ResponseData.error("请勿重复支付");
    	}
    	
    	if(paytype.equals("alipay")) {
        	String newWin = " target='_blank' ";
    		String payInfo = AliPayUtil.pay(order.getOrderNum(), order.getTjiage().toString(), order.getTname(), order.getTms());
    		
    		StringBuilder sb = new StringBuilder(payInfo);
    		sb.insert(6,newWin);
    		payInfo=sb.toString();
    		
    		//更新订单支付方式
    		order.setPayType("alipay");
    		orderService.updateById(order);
    		
    		return ResponseData.success(payInfo);
    	}else if(paytype.equals("wechatpay")) {
    		PrepayRequest request = new PrepayRequest();
    		Amount am = new Amount();
    		BigDecimal fen = order.getTjiage().multiply(new BigDecimal("100"));
    		am.setTotal(fen.intValue());
    		request.setAmount(am);
    		request.setDescription(order.getTname());
    		request.setOutTradeNo(order.getOrderNum());
    		request.setNotifyUrl("http://chat.uapps.cn/wxPayNotice");
    		PrepayResponse pr = new PrepayResponse();
			try {
				pr = WechatPayUtils.prepay(request);
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println(e);
				return ResponseData.error("支付参数错误");
			}
			
			//更新订单支付方式
    		order.setPayType("wechatpay");
    		orderService.updateById(order);
			
			return ResponseData.success(pr);
    	}else {
    		return ResponseData.error("支付参数错误");
    	}
    }
    
    
    
    
    /**
     * 支付操作
     *
     * @author fengshuonan
     * @throws AlipayApiException 
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping("/queryPayStatus")
    @ResponseBody
    public ResponseData queryPayStatus(String orderNumber,String paytype) throws AlipayApiException {
    	
    	
    	if(ToolUtil.isEmpty(paytype)||ToolUtil.isEmpty(orderNumber)) {
    		return ResponseData.error("支付参数错误");
    	}
    	
    	Order order = orderService.getOne(new QueryWrapper<Order>()
    			.eq("orderNum", orderNumber));
    	
    	if(order==null) {
    		return ResponseData.error("订单不存在");
    	}
    	
    	if(paytype.equals("alipay")) {
    		Map<String,Object> resmap = AliPayUtil.queryOrderStatus(orderNumber);
    		System.out.println(resmap);
    		return ResponseData.success(resmap);
    	}else if(paytype.equals("wechatpay")) {
    		return ResponseData.success();
    	}else {
    		return ResponseData.error("支付参数错误");
    	}
    }
    
    
    @RequestMapping(value="/payNoticeApi",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Object> payNoticeApi(HttpServletRequest request) throws AlipayApiException {
    	
    	Map<String, String[]> paramsMap = request.getParameterMap();
    	Map<String, String> resmap = new HashMap<String, String>();
    	
    	for (Object o : paramsMap.keySet()) {
            String name = (String) o;
            String[] values = (String[]) paramsMap.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            resmap.put(name, valueStr);
        }
    	
    	System.out.println("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
    	
    	System.out.println(resmap);
    	
    	boolean signVerified = AlipaySignature.rsaCheckV1(resmap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
    	
    	System.out.println(signVerified);
//    	{
//    		gmt_create=2023-08-31 13:44:25, 
//    		charset=utf-8, 
//    		gmt_payment=2023-08-31 13:44:31,
//    		notify_time=2023-08-31 13:44:34, 
//    		subject=微盟公众号变现小程序, 
//    		sign=rNSSCYHgIqG+rbyv7HF6GU1y2Ax9A3CILJWGsm1lgit8bOGhFxSAMVklRlOCbIMC5z5uud+7jU9Ngw40ysVvH56dz7hp6L2i52Qzunz0KEWn9IuPTny0Gmor+AzGpAsvwm4T3Rg1AABbRr7DtZiM+Ymt4SSeBfYKuZqwmmXoraN2tle7wReYW5tbTT70NvAn0Sjhjw/tZWHTo3UCUIY6/e+DtAmxuvZwqMiwc6eu7iMFYzhvCpeiYUB3WECqwSXg74xNh4CdoVVtknsDFOCBrI5wI4YvaOHBTHBXUNYKJGRI/whjk9bLnm1z7OFVQskYyLnybuE4JHYDQh6WtXFNAQ==, 
//    		buyer_id=2088722009393423, 
//    		body=精选公众号变现必备小程序功能，超全运营培训支持，帮助商家通过社群/公众号/朋友圈进行变现赚钱, 
//    		invoice_amount=399.00, 
//    		version=1.0, 
//    		notify_id=2023083101222134433093420500825430, 
//    		fund_bill_list=[{"amount":"399.00","fundChannel":"ALIPAYACCOUNT"}], 
//    		notify_type=trade_status_sync, 
//    		out_trade_no=OT1693460654821262144903072, 
//    		total_amount=399.00, 
//    		trade_status=TRADE_SUCCESS, 
//    		trade_no=2023083122001493420500737905, 
//    		auth_app_id=9021000125689818, 
//    		receipt_amount=399.00, 
//    		point_amount=0.00,
//    		buyer_pay_amount=399.00, 
//    		app_id=9021000125689818, 
//    		sign_type=RSA2, 
//    		seller_id=2088721009333804
//    	}
    	if(signVerified) {
    		String trade_status = resmap.get("trade_status");
    		String out_trade_no = resmap.get("out_trade_no");
    		String receipt_amount = resmap.get("receipt_amount");
    		String gmt_payment = resmap.get("gmt_payment");
    		String trade_no = resmap.get("trade_no");
    		
    		Order order = orderService.getOne(new QueryWrapper<Order>()
    				.eq("orderNum", out_trade_no));
    		
    		order.setPayTime(gmt_payment);
    		order.setShifu(new BigDecimal(receipt_amount));
    		order.setState(1);
    		order.setPayType("alipay");
    		order.setAliOrder(trade_no);
    		Tpls tpl = tplsService.getById(order.getTid());
    		order.setDownUrl(tpl.getPics());
    		
    		if("TRADE_SUCCESS".equals(trade_status)) {
    			orderService.updateById(order);
    			return new ResponseEntity<>("success",HttpStatus.OK);//返回success ,让支付宝不在重复调起回调
    		}
    		
    	}
    	return null;//返回success ,让支付宝不在重复调起回调
    }
    
    

}